package com.xyrl.project.common.store.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyrl.common.util.ObjectUtil;
import com.xyrl.common.util.RedisUtil;
import com.xyrl.common.util.StringUtil;
import com.xyrl.project.common.common.enu.AttImageUseType;
import com.xyrl.project.common.common.service.AttachmentService;
import com.xyrl.project.common.constant.DictConstant;
import com.xyrl.project.common.constant.XyrlConstant;
import com.xyrl.project.common.csr.entity.CsrUser;
import com.xyrl.project.common.csr.enu.CsrUserType;
import com.xyrl.project.common.csr.service.CsrUserService;
import com.xyrl.project.common.csr.vo.CsrApplyVo;
import com.xyrl.project.common.csr.vo.CsrRegisterVo;
import com.xyrl.project.common.domian.MsgCodeVo;
import com.xyrl.project.common.log.enu.SmsSendType;
import com.xyrl.project.common.store.dao.StoreAuthMapper;
import com.xyrl.project.common.store.dao.StoreCsrMapper;
import com.xyrl.project.common.store.dao.StoreMapper;
import com.xyrl.project.common.store.entity.Store;
import com.xyrl.project.common.store.entity.StoreAuth;
import com.xyrl.project.common.store.entity.StoreCsr;
import com.xyrl.project.common.store.entity.StoreLegal;
import com.xyrl.project.common.store.enu.StoreAuthStatus;
import com.xyrl.project.common.store.enu.StoreStatus;
import com.xyrl.project.common.store.enu.StoreStatusNode;
import com.xyrl.project.common.store.enu.StoreType;
import com.xyrl.project.common.store.service.StoreAuthService;
import com.xyrl.project.common.store.service.StoreService;
import com.xyrl.project.common.store.vo.StoreSalesVo;
import com.xyrl.project.common.store.vo.StoreVo;
import com.xyrl.project.common.system.entity.User;
import com.xyrl.project.common.system.service.DictionaryService;
import com.xyrl.project.common.system.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * @author 徐恩源
 * @version 1.0
 * @className StoreServiceImpl.java
 * @company 重庆星纭融链科技公司
 * @date 2019-12-30 10:32:48
 * @Description 商户serviceImpl
 */
@Service
@Slf4j
public class StoreServiceImpl extends ServiceImpl<StoreMapper, Store> implements StoreService {

    @Autowired
    private StoreAuthMapper storeAuthMapper;
    @Autowired
    private StoreCsrMapper storeCsrMapper;
    @Autowired
    private CsrUserService csrUserService;
    @Autowired
    private AttachmentService attachmentService;
    @Autowired
    private UserService userService;
    @Autowired
    private DictionaryService dictionaryService;


    @Override
    public StoreVo findByCsrUserId(long csrUserId) {
        return baseMapper.findByCsrUserId(csrUserId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Store register(CsrRegisterVo registerVo, Long salesId) {
        // 检查手机号
        checkMobile(registerVo.getMobile(), salesId);
        // 检查验证码
        checkVerifyCode(registerVo.getMobile(), registerVo.getVerifyCode());

        CsrUser csrUser = csrUserService.getByMobile(registerVo.getMobile());
        if (null != csrUser) {
            // 修改账号信息
            csrUser.setName(registerVo.getName());
            csrUserService.saveOrUpdate(csrUser);
            // 修改商户信息
            StoreVo storeVo = this.findByCsrUserId(csrUser.getId());
            if (null != storeVo) {
                Store store = new Store();
                BeanUtils.copyProperties(registerVo, store);
                store.setName(registerVo.getStoreName());
                store.setUpdateTime(new Date());
                store.setUpdateUserId(salesId);
                super.saveOrUpdate(store);
                return store;
            } else {
                return saveStore(registerVo, salesId, csrUser.getId());
            }
        } else {
            // 保存用户信息
            csrUser = new CsrUser();
            BeanUtils.copyProperties(registerVo, csrUser);
            csrUser.setVersion(0);
            csrUser.setUserType(CsrUserType.admin);
            csrUser.setCreateTime(new Date());
            csrUser.setCreateUserId(salesId);
            csrUser.setCreditPrice(BigDecimal.ZERO);
            csrUser.setSalt(RandomUtil.randomString(20));
            csrUserService.saveOrUpdate(csrUser);
            // 保存商户
            return saveStore(registerVo, salesId, csrUser.getId());
        }
    }

    /**
     * 检查手机号
     *
     * @param mobile
     * @param salesId
     */
    @Override
    public void checkMobile(String mobile, Long salesId) {
        Store store = baseMapper.findByAdminMobile(mobile);
        if (null != store) {
            // 商户注册成功，当前客户经理已是商户客户经理
            boolean noSendFlag = StoreStatus.success.equals(store.getStatus())
                    || salesId.equals(store.getSalesId());
            Assert.isFalse(noSendFlag, "手机号码已存在");
        }
    }

    /**
     * 检查验证码
     *
     * @param mobile
     * @param verifyCode
     * @author 徐恩源
     * @date 2020-01-03 16:40:04
     */
    private void checkVerifyCode(String mobile, String verifyCode) {
        //缓存短信发送信息
        String cacheKey = StringUtil.concat(XyrlConstant.ALIYUN_SMS_VALID_TERM, SmsSendType.registerCode.name(), ":", mobile);
        MsgCodeVo msgCodeVo = RedisUtil.getData(cacheKey, MsgCodeVo.class);
        boolean verifyFlag = null == msgCodeVo || !msgCodeVo.getCode().equals(verifyCode);
        Assert.isFalse(verifyFlag, "验证码错误");
    }





    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updateStoreLogo(Long userId, Long storeId, String path) {
        Store store = super.getById(storeId);
        if (null == store) {
            return "商户不存在";
        }
        if(store.getCsrUserId().intValue()==userId.intValue()){
            return "不能修改非本人";
        }
        store.setLogo(path);
        updateById(store);
        attachmentService.changeImageUsePath(storeId, AttImageUseType.storeLogo, path, store.getLogo());
        return "";
    }



    @Override
    public Page<StoreVo> findPage(Page<StoreVo> page, StoreStatus storeStatus, long salesId, String search, Boolean isDesc) {
        Map<String, Object> map = new HashMap<>(4);
        map.put("salesId", salesId);
        map.put("search", search);
        if (null != storeStatus) {
            map.put("storeStatus", storeStatus.getValue());
        }
        String orderBy = null == isDesc || isDesc ? "desc" : "asc";
        map.put("orderBy", orderBy);
        return baseMapper.findPage(page, map);
    }

    @Override
    public StoreVo findStoreVoById(long storeId) {
        Store store = super.getById(storeId);
        if (null == store) {
            return null;
        }
        StoreVo storeVo = new StoreVo();
        BeanUtils.copyProperties(store, storeVo);
        CsrUser csrUser = csrUserService.getById(store.getCsrUserId());
        storeVo.setCsrName(csrUser.getName());
        storeVo.setCsrMobile(csrUser.getMobile());
        return storeVo;
    }

    @Override
    public StoreSalesVo findStoreSalesVoById(long csrUserId) {
        CsrUser csrUser = csrUserService.getById(csrUserId);
        if (null == csrUser) {
            return null;
        }
        StoreSalesVo storeSalesVo = new StoreSalesVo();
        // 查询客户电话
        String servicePhone = dictionaryService.findValueByKey(DictConstant.SERVICE_PHONE);
        storeSalesVo.setServicePhone(servicePhone);

        // 查询商户信息
        StoreVo storeVo = baseMapper.findByCsrUserId(csrUserId);
        if (null != storeVo) {
            storeSalesVo.setStoreVo(storeVo);
        } else {
            storeVo = new StoreVo();
            storeVo.setName("商户" + StringUtils.substring(csrUser.getMobile(), 8));
            storeSalesVo.setStoreVo(storeVo);
            return storeSalesVo;
        }

        // 客户经理信息
        if (ObjectUtil.isNotEmpty(storeVo.getSalesId())) {
            User salesUser = userService.getById(storeVo.getSalesId());
            storeSalesVo.setSalesNo(salesUser.getUserId());
            storeSalesVo.setSalesName(salesUser.getAccount());
            storeSalesVo.setSalesMobile(salesUser.getMobile());
            if(ObjectUtil.isNotEmpty(salesUser.getAvatar())){
                storeSalesVo.setSalesHead(salesUser.getAvatar());
            }
        }
        return storeSalesVo;
    }



    @Override
    public long applyStore(long csrUserId, CsrApplyVo applyVo) {
        String storeName = "商户" + applyVo.getMobile().substring(8);
        Store store = null;
        StoreVo storeVo = this.findByCsrUserId(csrUserId);
        if (null != storeVo) {
            // 已是（进货商+供货商）不能再申请; 同一类型不可重复申请
            boolean noApplyFlag = StoreType.all.equals(storeVo.getStoreType())
                    || applyVo.getStoreType().equals(storeVo.getStoreType());
            Assert.isFalse(noApplyFlag, "请勿重复提交申请信息");

        }
        // 修改账号信息
        CsrUser csrUser = new CsrUser();
        csrUser.setId(csrUserId);
        csrUser.setName(applyVo.getName());
        csrUserService.updateById(csrUser);
        // 修改门店信息
        if (null != storeVo) {
            store = new Store();
            BeanUtils.copyProperties(applyVo, store);
            store.setId(storeVo.getId());
            store.setName(storeName);
            store.setStoreType(StoreType.all);
            super.updateById(store);
        } else {
            store = new Store();
            BeanUtils.copyProperties(applyVo, store);
            store.setName(storeName);
            store.setStatus(StoreStatus.create);
            store.setStatusNote(StoreStatusNode.create);
            store.setSalesId(null);
            store.setStaffNum(0);
            store.setCreateUserId(-1L);
            store.setCreateTime(new Date());
            store.setVersion(0);
            store.setCsrUserId(csrUserId);
            super.saveOrUpdate(store);
            // 保存商户和用户关联表
            StoreCsr storeCsr = new StoreCsr();
            storeCsr.setStoreId(store.getId());
            storeCsr.setCsrUserId(csrUserId);
            storeCsrMapper.insert(storeCsr);
            // 保存商户验证
            this.saveStoreAuth(store.getId());
        }
        return store.getId();
    }

    @Override
    public Store findById(Long id) {
        return super.getById(id);
    }

    @Override
    public Store checkStoreBySalesId(Long id, Long salesId) {
        if (null == id || null == salesId) {
            return null;
        }
        Store store = this.findById(id);
        if (null == store || !salesId.equals(store.getSalesId())) {
            return null;
        }
        return store;
    }

    @Override
    public Store checkOpStorePermission(Long id, Long salesId) {
        Assert.isTrue(null != id && null != salesId, "商户不存在");
        Store store = this.findById(id);
        Assert.isTrue(null != store && salesId.equals(store.getSalesId()), "操作失败，并非您的商户");
        return store;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStore(StoreVo storeVo, Long saleId) {
        Store oldStore = this.checkStoreBySalesId(storeVo.getId(), saleId);
        Assert.notNull(oldStore, "商户不存在");
        // 修改商户
        Store mStore = new Store();
        BeanUtils.copyProperties(storeVo, mStore, "status");
        super.updateById(mStore);
        // 处理头像
        if (ObjectUtil.isNotEmpty(storeVo.getLogo())) {
            attachmentService.handleAttImageUsePath(storeVo.getId(), AttImageUseType.storeLogo, storeVo.getLogo(), oldStore.getLogo());
        }
    }


    /**
     * 保存门店信息
     *
     * @param registerVo
     * @param salesId
     * @param csrUserId
     * @author 徐恩源
     * @date 2019-12-31 15:01:28
     */
    private Store saveStore(CsrRegisterVo registerVo, long salesId, Long csrUserId) {
        // 保存商户信息
        Store store = new Store();
        BeanUtils.copyProperties(registerVo, store);
        store.setName(registerVo.getStoreName());
        store.setStatus(StoreStatus.create);
        store.setStatusNote(StoreStatusNode.create);
        store.setSalesId(salesId);
        store.setStaffNum(0);
        store.setCreateUserId(salesId);
        store.setCreateTime(new Date());
        store.setVersion(0);
        store.setCsrUserId(csrUserId);
        super.save(store);
        // 保存商户和用户关联表
        StoreCsr storeCsr = new StoreCsr();
        storeCsr.setStoreId(store.getId());
        storeCsr.setCsrUserId(csrUserId);
        storeCsrMapper.insert(storeCsr);
        // 保存商户验证
        this.saveStoreAuth(store.getId());
        return store;
    }

    public StoreAuth saveStoreAuth(long storeId) {
        StoreAuth storeAuth = new StoreAuth();
        storeAuth.setId(storeId);
        storeAuth.setRealNameAuth(StoreAuthStatus.NO);
        storeAuth.setLicenseAuth(StoreAuthStatus.NO);
        storeAuth.setBankList(StoreAuthStatus.NO);
        storeAuth.setBuyerTradeRecord(StoreAuthStatus.NO);
        storeAuth.setBuyerStorePic(StoreAuthStatus.NO);
        storeAuth.setBuyerContract(StoreAuthStatus.NO);
        storeAuth.setSellerContract(StoreAuthStatus.NO);
        storeAuth.setSellerPic(StoreAuthStatus.NO);
        int count = storeAuthMapper.insert(storeAuth);
        if (count > 0) {
            return storeAuth;
        }
        return null;
    }




    @Override
    public boolean isPersonVerify(Long storeId) {
        Store store = this.baseMapper.selectById(storeId);
        if (ObjectUtil.isEmpty(store)) {
            return false;
        }
        //商户状态处于创建  跟踪 时未通过实名认证
        if (!store.getStatus().equals(StoreStatus.create.getValue()) && !store.getStatus().equals(StoreStatus.follow.getValue())) {
            return true;
        }
        return false;
    }
}
